package com.yang.web.featuretest.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yang.web.featuretest.config.GlobalInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: yangzhiwei
 * @Date: 2021/8/31 15:41
 */

public class JWTUtil {

    public final  static String SECRET = "my_screat";
    private static final Logger logger = LoggerFactory.getLogger(GlobalInterceptor.class);
    public static String creatToken(String properity, String token) {

        logger.info("test");

        Map<String,Object> header = new HashMap<>();
        header.put("header","header");
        String jwt = JWT.create()
                .withHeader(header)
                //声明属性名 和 value
                .withClaim(properity,token)
                .withClaim("杨", "乐")

                //设置负载
                .withIssuer("签发人")
                .withSubject("主题")
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET));
        return jwt;
    }

    public static Map<String, Claim> decode(String token) {
        DecodedJWT decodedJWT =  JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        // 解密后的token等于 header + payload + signature
        String header = decodedJWT.getHeader();

        System.out.println();

        String payLoad = decodedJWT.getPayload();
        String signature = decodedJWT.getSignature();
        String resToken = decodedJWT.getToken();
        String alg = decodedJWT.getAlgorithm();
        String type = decodedJWT.getType();
        return decodedJWT.getClaims();

    }

    public static void main(String[] args) {
//        String token = creatToken();
//        Map res = decode(token);
//        System.out.println(res);
    }
}
